package com.kefu.service.impl;

import com.kefu.dto.AdminDTO;
import com.kefu.dto.AdminLoginRequest;
import com.kefu.entity.Admin;
import com.kefu.repository.AdminRepository;
import com.kefu.service.AdminService;
import com.kefu.util.JwtUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;

@Service
public class AdminServiceImpl implements AdminService {

    @Autowired
    private AdminRepository adminRepository;

    @Autowired
    private BCryptPasswordEncoder passwordEncoder;

    @Autowired
    private JwtUtil jwtUtil;

    @Override
    public Map<String, Object> login(AdminLoginRequest request) {
        // 查询客服信息
        Admin admin = adminRepository.findByUsername(request.getUsername())
                .orElseThrow(() -> new RuntimeException("用户名不存在"));

        // 验证密码
//        if (!passwordEncoder.matches(request.getPassword(), admin.getPassword())) {
//            throw new RuntimeException("密码错误");
//        }

        // 取消加密，直接比对明文密码（仅测试用）
        if (!request.getPassword().equals(admin.getPassword())) {
            throw new RuntimeException("密码错误");
        }

        // 生成token
        //String token = jwtUtil.generateToken(admin.getId());
        // 最简单的方式：用管理员ID+当前时间戳拼接作为token
        String token = admin.getId() + "_" + System.currentTimeMillis();

        // 更新在线状态
        admin.setStatus(1);
        adminRepository.save(admin);

        // 构建返回结果
        Map<String, Object> result = new HashMap<>();
        result.put("token", token);

        AdminDTO adminDTO = new AdminDTO();
        adminDTO.setId(admin.getId());
        adminDTO.setUsername(admin.getUsername());
        adminDTO.setName(admin.getName());
        adminDTO.setStatus(admin.getStatus());
        result.put("admin", adminDTO);

        return result;
    }

    @Override
    public AdminDTO getAdminById(String adminId) {
        Admin admin = adminRepository.findById(adminId)
                .orElseThrow(() -> new RuntimeException("客服不存在"));

        AdminDTO dto = new AdminDTO();
        dto.setId(admin.getId());
        dto.setUsername(admin.getUsername());
        dto.setName(admin.getName());
        dto.setStatus(admin.getStatus());
        return dto;
    }

    @Override
    public boolean updateStatus(String adminId, int status) {
        if (status < 0 || status > 2) {
            throw new RuntimeException("无效的状态值");
        }

        Admin admin = adminRepository.findById(adminId)
                .orElseThrow(() -> new RuntimeException("客服不存在"));

        admin.setStatus(status);
        adminRepository.save(admin);
        return true;
    }
}
